package com.solute.utils.services;

import java.io.IOException;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.solute.domain.ImageGroupVO;
import com.solute.domain.ImageVO;
import com.solute.utils.image.ImageRepository;
import com.solute.utils.services.dao.ImageDao;

@Service
public class ImageService {
	
	private static final Logger logger = LoggerFactory.getLogger(ImageService.class);
	
	private @Autowired ImageDao dao;
	private @Autowired ImageRepository imageRepository;
	
	@Transactional
	public void add(String id, MultipartFile image) {
		String path ;
		try {
			path = imageRepository.store(id, image);
		} catch(IOException e) {
			logger.error(e.getMessage(), e);
			throw new RuntimeException(e);
		}
		ImageVO img = new ImageVO();
		img.setId(id);
		img.setPath(path);
		
		dao.insertImage(img);
	}
	
	@Transactional
	public String createImageGroup(String []ids) {
		String gid = UUID.randomUUID().toString();
		for(String id : ids) 
			dao.insertImageGroup(new ImageGroupVO(gid, id));
		
		return gid;
	}
	
	@Transactional
	public void removeAll() {
		dao.deleteImageGroups();
		dao.deleteImages();
	}
}
